package com.ithiema.ui;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.util.*;

public class LoginJFrame extends JFrame implements MouseListener {
    //loginJFrame 表示登录界面
    //登录相关代码都写在这里

    //注册逻辑涉及IO知识，先不做要求
//    static ArrayList<User> list = new ArrayList<>();
//
//    static {
//        list.add(new User("zhangsan", "zhangsan123"));
//        list.add(new User("lisi", "123456lisi"));
//        list.add(new User("steve", "88888888"));
//    }
    private static final int times = 5;

    JTextField username = new JTextField();
    JPasswordField password = new JPasswordField();
    JTextField codeTextField = new JTextField();
    JLabel codePng = new JLabel();
    JButton login = new JButton();
    JButton register = new JButton();



    public LoginJFrame() {
        //初始化界面
        initJFrame();

        //在这个界面中显示内容
        initView();

        //让显示显示出来，建议写在最后
        this.setVisible(true);

    }

    public void initView() {

        //1.添加用户名文字
        JLabel usernameText = new JLabel(new ImageIcon("image/login/用户名.png"));
        usernameText.setBounds(116, 135, 47, 17);
        this.getContentPane().add(usernameText);

        //2.添加用户名输入框

        username.setBounds(195, 134, 200, 30);
        this.getContentPane().add(username);

        //3.添加密码文字
        JLabel passwordText = new JLabel(new ImageIcon("image/login/密码.png"));
        passwordText.setBounds(130, 195, 32, 16);
        this.getContentPane().add(passwordText);

        //4.密码输入框
        password.setBounds(195, 195, 200, 30);
        this.getContentPane().add(password);

        //验证码提示
        JLabel codeText = new JLabel(new ImageIcon("image/login/验证码.png"));
        codeText.setBounds(133, 256, 56, 21);
        this.getContentPane().add(codeText);

        //验证码输入框
        codeTextField.setBounds(195, 256, 100, 30);
        this.getContentPane().add(codeTextField);

        //验证码图片生成
        Code code = new Code();
        codePng.setText(code.getCode());
        //绑定鼠标事件
        codePng.addMouseListener(this);
        codePng.setBounds(300, 256, 50, 30);
        this.getContentPane().add(codePng);

        //添加登录按钮
        login.setBounds(123, 310, 128, 47);
        login.setIcon(new ImageIcon("image/login/登录按钮.png"));
        //去除按钮边框
        login.setBorderPainted(false);
        //去除按钮的背景
        login.setContentAreaFilled(false);
        //给登录按钮绑定鼠标事件
        login.addMouseListener(this);
        //将按钮添加到页面中
        this.getContentPane().add(login);

        //添加注册按钮
        register.setBounds(256, 310, 120, 47);
        register.setIcon(new ImageIcon("image/login/注册按钮.png"));
        //去除按钮边框
        register.setBorderPainted(false);
        //去除按钮背景
        register.setContentAreaFilled(false);
        //给注册按钮绑定鼠标事件
        register.addMouseListener(this);
        //添加到页面
        this.getContentPane().add(register);

        //添加背景图片
        JLabel background = new JLabel(new ImageIcon("image/login/background.png"));
        background.setBounds(0, 0, 470, 390);
        this.getContentPane().add(background);

        InputLatestLogin();
    }

    private void InputLatestLogin() {
        String info = null;
        try {
            info = getLatestLogin();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(info == null)
        {
            return;
        }
        String name = info.split("&")[0].split("=")[1];
        String pass = info.split("&")[1].split("=")[1];
        username.setText(name);
        password.setText(pass);
    }


    private void initJFrame() {
        //初始化界面
        //在创建登录界面的时候，同时给这个界面设置一些信息
        this.setSize(470, 418);
        //设置界面的标题
        this.setTitle("拼图 登录");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        //同时出现的只有一个界面
        //WindowConstants.EXIT_ON_CLOSE=3 为常量，也可以用3传入参数
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //取消内部默认布局
        this.setLayout(null);
    }

    public void showJDialog(String content)
    {
        //创建一个弹框对象
        JDialog jDialog = new JDialog();
        //给弹框设置大小
        jDialog.setSize(200,150);
        //让弹框置顶
        jDialog.setAlwaysOnTop(true);
        //让弹框居中
        jDialog.setLocationRelativeTo(null);
        //弹框不关闭永远无法操作下面的界面
        jDialog.setModal(true);

        //创建JLabel对象管理文字并添加到弹框当中
        JLabel Warning = new JLabel();
        Warning.setText(content);
        Warning.setBounds(100,65,200,150);
        jDialog.getContentPane().add(Warning);

        //显示弹框
        jDialog.setVisible(true);
    }

    public String getLatestLogin() throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("LatestLogin.txt"));
        String line = br.readLine();
        br.close();
        return line;
    }
    public ArrayList<User> getInfo() throws IOException
    {
        ArrayList<User> userList = new ArrayList<>();
        ArrayList<String> list = new ArrayList<>();

        BufferedReader br = new BufferedReader(new FileReader("userInfo.txt"));

        String line;
        while((line=br.readLine())!=null)
        {
            list.add(line);
        }

        br.close();

        for (String user : list) {
            String userName = user.split("&")[0].split("=")[1];
            String password = user.split("&")[1].split("=")[1];
            int count = Integer.parseInt(user.split("&")[2].split("=")[1]);

            userList.add(new User(userName,password,count));
        }
        return userList;
    }

    @Override
    public void mouseClicked(MouseEvent e)
    {
            ArrayList<User> list;
            if(e.getSource() == login)
            {
                System.out.println("点击了登录按钮");
                //获取两个文本输入框中的内容
                String usernameInput = username.getText();
                String passwordInput = password.getText();
                //获取用户输入的验证码
                String codeInput = codePng.getText();

                //获取数据库中的账号密码信息
                try {
                    /*
                    每一次都读取也可以时当前打开次注册的用户刷新到
                    内存中的list
                    */
                    list = getInfo();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

                //创建一个User对象
                User userInfo = new User(usernameInput,passwordInput);
                System.out.println("用户输入的用户名为："+usernameInput);
                System.out.println("用户输入的密码为"+passwordInput);

                //判空
                if(codeInput.length()==0)
                {
                    //验证码为空
                    showJDialog("验证码不能为空");
                    return;
                }
                else if(usernameInput.length()==0||passwordInput.length() == 0)
                {
                    //校验用户名和密码是否为空
                    System.out.println("用户名或者密码为空");

                    //调用showJDialog方法并展示弹框
                    showJDialog("用户名或者密码为空");
                    return;
                }

                //判断验证码
                if(!codeInput.equals(codePng.getText()))
                {
                    showJDialog("验证码输入错误");
                    codeTextField.setText("");
                    return;
                }

                //判断账号密码是否符合要求
                try {
                    if(contains(userInfo,list))
                    {
                        System.out.println("用户名密码正确");
                        writeLatestInfo(userInfo.toString());
                        //关闭登录界面
                        this.setVisible(false);
                        //打开游戏的主界面
                        //需要把当前登录的用户名传递给游戏界面
                        new GameJFrame(usernameInput);
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }

            else if(e.getSource() == register)
            {
                System.out.println("点击了注册按钮");
                this.setVisible(false);
                new RegisterJFrame();
            }
            else if(e.getSource() == codePng)
            {
                System.out.println("更换验证码");
                //获取一个新的验证码
                Code c = new Code();
                String code = c.getCode();
                codePng.setText(code);
            }
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        //按下不松
        if(e.getSource() == login)
        {
            login.setIcon(new ImageIcon("image/login/登录按下.png"));
        }
        else if(e.getSource() == register)
        {
            login.setIcon(new ImageIcon("image/login/注册按下.png"));
        }
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        //松开按钮
        if(e.getSource() == login)
        {
            login.setIcon(new ImageIcon("image/login/登录按钮.png"));
        }
        else if(e.getSource() == register)
        {
            login.setIcon(new ImageIcon("image/login/注册按钮.png"));
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    public void writeLatestInfo(String content) throws IOException
    {
        BufferedWriter bw = new BufferedWriter(new FileWriter("LatestLogin.txt"));

        bw.write(content);

        bw.close();
    }
    public void writeInfo(String content,boolean append) throws IOException
    {
        BufferedWriter bw = new BufferedWriter(new FileWriter("userInfo.txt",append));

        bw.write(content);

        bw.newLine();

        bw.close();
    }

    public boolean HasUsername(String username) throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("userinfo.txt"));

        ArrayList<String> list = new ArrayList<>();
        String line;
        while ((line=br.readLine())!=null)
        {
            list.add(line);
        }

        for (String s : list) {
            String user = s.split("&")[0].split("=")[1];
            if(user.equals(username))
            {
                return true;
            }
        }
        return false;
    }
    //判断用户在集合中是否存在
    public boolean contains(User userInput,ArrayList<User> list) throws IOException {
        boolean flag = false;
        //先判断用户名是否存在
        if(!HasUsername(userInput.getUserName()))
        {
            System.out.println("用户名不存在");
            showJDialog("用户名不存在");
            return false;
        }
        //判断账号密码是否匹配
        for (int i = 0; i < list.size(); i++)
        {
            User rightUser = list.get(i);
            //要先找到对应的用户名才能进行下一步操作
            if(userInput.getUserName().equals(rightUser.getUserName()))
            {
                if(rightUser.getCount()<times)
                {
                    if(userInput.equals(rightUser))
                    {
                        //用户名密码匹配
                        //将次数归0
                        rightUser.setCount(0);
                        flag = true;
                    }
                    else
                    {
                        int count = rightUser.getCount();
                        count++;
                        //密码错误
                        showJDialog("密码错误，还剩下"+(times-count)+"次机会");
                        rightUser.setCount(count);
                        password.setText("");
                        //获取一个新的验证码
                        Code c = new Code();
                        String code = c.getCode();
                        codePng.setText(code);
                        codeTextField.setText("");
                    }
                }
                else
                {
                    //次数已用完
                    showJDialog("您的账户已冻结！");
                    username.setText("");
                    password.setText("");
                    codeTextField.setText("");
                    return false;
                }
            }
            list.set(i,rightUser);
        }
        for (int i = 0; i < list.size(); i++) {
            if(i == 0)
            {
                writeInfo(list.get(i).toString(),false);
            }
            else
            {
                writeInfo(list.get(i).toString(),true);
            }
        }
        if(flag)
        {
            return true;
        }
        return false;
    }

}
